#!/usr/bin/env node
const {execSync} = require('child_process');

function copyToClipboard(text) {
  switch (process.platform) {
    case "darwin": // macOS
      execSync(`echo "${text}" | pbcopy`);
      break;
    case "win32": // Windows
      const fs = require('fs');
      const os = require('os');
      const path = require('path');
      const tempFile = path.join(os.tmpdir(), 'clipboard.txt');
      // 使用 UTF-8 with BOM 编码写入文件，避免中文乱码
      const BOM = Buffer.from([0xEF, 0xBB, 0xBF]);
      fs.writeFileSync(tempFile, BOM + Buffer.from(text, 'utf8'));
      try {
        // 使用 PowerShell 的 Set-Clipboard 命令，更好地支持 UTF-8
        execSync(`powershell -command "Get-Content '${tempFile}' -Encoding UTF8 | Set-Clipboard"`, { shell: 'powershell.exe' });
      } catch (error) {
        // 如果 PowerShell 方法失败，回退到原来的方法
        execSync(`type "${tempFile}" | clip`, { shell: 'cmd.exe' });
      } finally {
        fs.unlinkSync(tempFile);
      }
      break;
    case "linux": // Linux (需 xclip 或 xsel)
      execSync(`echo "${text}" | xclip -selection clipboard`);
      break;
    default:
      throw new Error("不支持的平台");
  }
}


const dayjs = require('dayjs');
const date = process.argv[2] || process.env.DATE;
const author = process.argv[3] || 'chenxiang';
if (!author) {
  console.error('GIT_AUTHOR_EMAIL 未设置');
  process.exit(1);
}
const currentDate = dayjs(date).format('YYYY-MM-DD 00:00:00');
const untilDate = dayjs(date).format('YYYY-MM-DD 23:59:59');
const since = currentDate;
const gitCmd = `git log --since="${since}" --until="${untilDate}" --author="${author}" --no-merges --pretty=format:"%s%n%b%n"`;
const raw = execSync(gitCmd, {encoding: 'utf8'});
if (!raw) {
  console.log('今日无提交，跳过。');
  process.exit(0);
}

// 按双换行符分割提交，每个提交包含主题和主体
const commitBlocks = raw.split('\n\n').filter(block => block.trim());
const numbered = commitBlocks.map((block, i) => {
  const lines = block.split('\n').filter(line => line.trim());
  const subject = lines[0]; // 第一行是主题
  const body = lines.slice(1); // 剩余行是主体
  
  if (body.length > 0) {
    // 如果有主体内容，缩进显示
    const bodyText = body.map(line => `    ${line}`).join('\n');
    return `${i + 1}. ${subject}\n${bodyText}`;
  } else {
    // 只有主题
    return `${i + 1}. ${subject}`;
  }
});

const title = `${date ?? dayjs().format('YYYY-MM-DD')} 日报 - ${author} \n`;
const result = title + numbered.join('\n');
copyToClipboard(result);
console.log('已复制到剪贴板');

